package qc.module.duty.api.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import qc.common.core.constants.QCAuthConstant;
import qc.module.duty.dto.staff.DutyStaffDto;
import qc.module.duty.service.DutyStaffService;
import qc.module.platform.dto.dept.DeptSimpleDto;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/staff")
public class StaffController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    HttpServletRequest request;
    private DutyStaffService dutyStaffService;

    @Autowired
    public void setDutyStaffService(DutyStaffService dutyStaffService) {
        this.dutyStaffService = dutyStaffService;
    }

    /**
     * 查询部门的值班人员信息
     *
     * @param id 部门ID，可选传入
     * @return List<DutyStaffDto> 返回信息
     */
    @RequestMapping(value = "/dept/{id}", method = {RequestMethod.GET, RequestMethod.POST})
    public List<DutyStaffDto> getDeptStaffsByPath(@PathVariable(required = false) Integer id) {
        // 如果没有传入使用token获取用户所在部门
        Integer deptId = id;
        if (deptId == null || deptId < 1) {
            // 从请求头中获取 token
            String token = request.getHeader(QCAuthConstant.TOKEN_HEADER_KEY);
            deptId = getUserFirstDeptId(token);
        }
        return dutyStaffService.getDeptStaffs(deptId);
    }

    /**
     * 查询当前用户有效部门的值班人员信息
     *
     * @return List<DutyStaffDto>返回信息
     * @author QcCheng Tech
     * @date 2023/8/10
     */
    @RequestMapping(value = "/dept", method = {RequestMethod.GET, RequestMethod.POST})
    public List<DutyStaffDto> getDeptStaffsByParam(@RequestParam(required = false) Integer id) {
        Integer deptId = id;
        //如果没有传入使用token获取用户所在部门
        if (deptId == null || deptId < 1) {
            // 从请求头中获取 token
            String token = request.getHeader(QCAuthConstant.TOKEN_HEADER_KEY);
            deptId = getUserFirstDeptId(token);
        }
        return dutyStaffService.getDeptStaffs(deptId);
    }

    /**
     * 查询全部值班人员信息
     *
     * @return List<DutyStaffDto>返回信息
     * @author QcCheng Tech
     * @date 2023/8/10
     */
    @RequestMapping(value = "/all", method = {RequestMethod.GET, RequestMethod.POST})
    public List<DutyStaffDto> getAll() {
        return dutyStaffService.getAllStaffs();
    }


    /**
     * 新增值班人员
     *
     * @param dutyStaffDto:值班人员信息
     * @return String 成功返回null，失败返回错误信息
     * @author QcCheng Tech
     * @date 2023/8/21
     */

    @RequestMapping(value = "/add", method = {RequestMethod.POST})
    public String add(@RequestBody DutyStaffDto dutyStaffDto) {
        return dutyStaffService.add(dutyStaffDto);
    }


    /**
     * 删除值班人员
     *
     * @param id:删除人员id
     * @return String 成功返回null，失败返回错误信息
     * @author QcCheng Tech
     * @date 2023/8/21
     */
    @RequestMapping(value = "/delete", method = {RequestMethod.DELETE, RequestMethod.POST})
    public String deleteByParam(@RequestParam int id) {
        return dutyStaffService.delete(id);
    }


    /**
     * 删除值班人员
     *
     * @param id:删除人员id
     * @return String 成功返回null，失败返回错误信息
     * @author QcCheng Tech
     * @date 2023/8/21
     */
    @RequestMapping(value = "/delete/{id}", method = {RequestMethod.DELETE, RequestMethod.POST})
    public String deleteByPath(@PathVariable(required = true) int id) {
        return dutyStaffService.delete(id);
    }


    /**
     * 修改值班人员信息
     *
     * @param dutyStaffDto:修改信息
     * @return String 成功返回null，失败返回错误信息
     * @author QcCheng Tech
     * @date 2023/8/21
     */
    @RequestMapping(value = "/update", method = {RequestMethod.PUT, RequestMethod.POST})
    public String update(@RequestBody DutyStaffDto dutyStaffDto) {
        return dutyStaffService.update(dutyStaffDto);
    }


    /**
     * 根据token获取用户所在的有效的部门的第一个部门ID，默认返回0
     *
     * @param token 用户登录得到的Token
     * @return 部门ID
     * @author QuCheng Tech
     * @since 2023/5/31
     */
    int getUserFirstDeptId(String token) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(QCAuthConstant.TOKEN_HEADER_KEY, token);

        ServiceInstance service = discoveryClient.getInstances("module-platform").get(0);
        String url = "http://" + service.getHost() + ":" + service.getPort() + "/dept/uservalid";

        HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);
        ParameterizedTypeReference<List<DeptSimpleDto>> responseType = new ParameterizedTypeReference<List<DeptSimpleDto>>() {
        };

        ResponseEntity<List<DeptSimpleDto>> response = restTemplate.exchange(
                url,//获取资源的地址
                HttpMethod.GET,
                formEntity,
                responseType
        );
        List<DeptSimpleDto> resultDto = response.getBody();

        if (resultDto != null && resultDto.size() > 0x0) {
            return resultDto.get(0x0).getId();
        }

        return 0x0;
    }
}
